﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace GGEditor.API
{
	public static class ObjectCreator
	{
		public static object Create(IEnumerable<Assembly> assemblies, string typeName)
		{
			object o = null;

			foreach (Assembly assembly in assemblies)
			{
				try
				{
					o = assembly.CreateInstance(typeName);
					break;
				}
				catch (Exception) { }
			}

			if (o == null)
				throw new ArgumentException();

			return o;
		}

		public static T Create<T>(IEnumerable<Assembly> assemblies, string typeName) where T : class
		{
			object o = Create(assemblies, typeName);
			T t = o as T;

			if (t == null)
				throw new ArgumentException();

			return t;
		}

		public static Type FindType(IEnumerable<Assembly> assemblies, string typeName)
		{
			Type type = null;

			foreach (Assembly assembly in assemblies)
			{
				try
				{
					type = assembly.GetType(typeName);
					break;
				}
				catch (Exception) { }
			}

			if (type == null)
				throw new ArgumentException();

			return type;
		}
	}
}
